package org.easy.tool.common;

import cn.hutool.core.util.URLUtil;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * @author Valley
 * Created by Valley on 2023/7/20 17:20
 */
public class WebUtil {

    /**
     * 功能：获取request对象
     */
    public static HttpServletRequest req(){
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        return ((ServletRequestAttributes)requestAttributes).getRequest();
    }

    /**
     * 功能：获取response对象
     */
    public static HttpServletResponse res(){
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        return ((ServletRequestAttributes)requestAttributes).getResponse();
    }

    /**
     * 功能：从请求中获取cookie值
     */
    public static String getCookie(String name) {
        Cookie[] cookies = req().getCookies();
        if (cookies != null){
            for (Cookie cookie : cookies) {
                if (StringUtil.equals(cookie.getName(), name)){
                    return cookie.getValue();
                }
            }
        }
        return "";
    }

    /**
     * 功能：获取当前请求的url链接
     */
    public static String getUrl(HttpServletRequest req) {
        String base = req.getRequestURL().toString();
        String param = req.getQueryString();
        return param == null ? base : base + "?" + param;
    }

    /**
     * 功能：从请求中获取cookie值
     */
    public static String getCookie(HttpServletRequest req, String name) {
        Cookie[] cookies = req.getCookies();
        if (cookies != null){
            for (Cookie cookie : cookies) {
                if (StringUtil.equals(cookie.getName(), name)){
                    return cookie.getValue();
                }
            }
        }
        return "";
    }

    /**
     * 功能：向响应中添加cookie
     */
    public static void addCookie(HttpServletResponse res, String name, String value, int expire) {
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
        cookie.setMaxAge(expire);
        res.addCookie(cookie);
    }

    /**
     * 功能：向响应中添加cookie
     */
    public static void addCookie(String name, String value, int expire) {
        addCookie(res(), name, value, expire);
    }

    /**
     * 功能：执行登录操作
     */
    public static String login(String userId) {
        String token = SecureUtil.aesEncode(userId);
        addCookie("login_token", token);
        return token;
    }

    /**
     * 功能：判断是否登录
     */
    public static boolean isLogin() {
        return StringUtil.isNotBlank(token());
    }

    /**
     * 功能：获取login_token解密结果
     */
    public static String token() {
        String token = getCookie("login_token");
        return SecureUtil.aesDecode(token);
    }

    /**
     * 功能：获取当前登录用户信息
     */
    public static String getUserId() {
        return token();
    }

    /**
     * 功能：退出登录，删除用户登录信息
     */
    public static void logout() {
        removeCookie("login_token");
    }

    /**
     * 功能：向响应中添加cookie，默认过期时间为30天
     */
    public static void addCookie(String name, String value) {
        addCookie(name, value, 60*60*24*30);
    }

    /**
     * 功能：从响应中删除某个cookie
     */
    public static void removeCookie(String name) {
        addCookie(name, "", 0);
    }

    /**
     * 功能：获取当前请求SessionID
     */
    public static String getSessionID(HttpServletRequest req) {
        return getCookie(req, "sessionID");
    }

    /**
     * 功能：获取当前请求SessionID
     */
    public static String getSessionID() {
        return getCookie("sessionID");
    }

    /**
     * 功能：向返回值中添加header
     */
    public static void addHeader(String name, String value) {
        res().addHeader(name, value);
    }

    /**
     * 功能：批量添加header，格式为name1, value1, name2, value2...
     */
    public static void addHeaders(String... headers) {
        for (int i = 0; i < headers.length; i+=2) {
            res().addHeader(headers[i], headers[i+1]);
        }
    }

    /**
     * 功能：从返回值中获取header值
     */
    public static String getHeader(String name) {
        return req().getHeader(name);
    }

    /**
     * 功能：获取请求url中的query参数
     */
    public static String getParam(String param) {
        return req().getParameter(param);
    }

    /**
     * 功能：获取json体参数
     */
    public static String getJsonParam() throws Exception{
        BufferedReader streamReader = new BufferedReader( new InputStreamReader(req().getInputStream(), StandardCharsets.UTF_8));
        StringBuilder sb = new StringBuilder();
        String inputStr;
        while ((inputStr = streamReader.readLine()) != null) {
            sb.append(inputStr);
        }
        return sb.toString();
    }

    /**
     * 功能：url编码
     */
    public static String urlEncode(String origin) {
        String[] split = origin.split("\\?");
        String url = URLUtil.encode(split[0]);
        if (split.length >= 2){
            String encode = URLUtil.encode(split[1]);
            url = url + "?" + encode;
        }
        return url;
    }

    /**
     * 功能：url解码
     */
    public static String urlDecode(String encode) {
        return URLUtil.decode(encode);
    }



}
